package com.longfa.ojbackendjudgeservice.codesandbox.impl;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.longfa.ojbackendcommon.common.ErrorCode;
import com.longfa.ojbackendcommon.exception.BusinessException;
import com.longfa.ojbackendjudgeservice.codesandbox.CodeSandbox;
import com.longfa.ojbackendmodel.model.codesandbox.ExecuteCodeRequest;
import com.longfa.ojbackendmodel.model.codesandbox.ExecuteCodeResponse;


/**
 * ClassName: RemoteCodeSandbox
 * Package: com.fa.oj.judge.codesandbox.impl
 * Description:远程代码沙箱（实际调用接口的沙箱）
 *
 * @Author:
 * @Create: 2024/4/23 - 15:03
 * @Version: v1.0
 */
public class RemoteCodeSandbox implements CodeSandbox {

    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
//        System.out.println("远程代码沙箱");
        // 在这里通过hutool工具类，访问远程接口      进行远程调用时，必须带上请求头
//        String url = "http://localhost:8088/main/executeCode"; //这是java原生代码沙箱
        String url = "http://139.9.86.41:8999/main/executeCode/docker"; //这是docker容器实现的代码沙箱
        // 这里通过hutool工具类，访问远程接口      进行远程调用时，必须带上请求头
        String requestJson = JSONUtil.toJsonStr(executeCodeRequest);
        String responseStr = HttpUtil.createPost(url)
                .body(requestJson)
                .header(AUTH_REQUEST_HEADER, AUTH_REQUEST_SECRET)
                .execute()
                .body();
        if (CharSequenceUtil.isBlank(responseStr)) {
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR,"executeCode sandbox exception! responseStr = {}" + responseStr);
        }
        ExecuteCodeResponse executeCodeResponse = JSONUtil.toBean(responseStr, ExecuteCodeResponse.class);
        return executeCodeResponse;
    }
}
